﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MockContinuationSource.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// <summary>
//   Defines the MockContinuationSource type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Threading.Mocks
{
    using System;
    using System.Collections.Generic;
    using System.Threading;

    public class MockContinuationSource : IContinuationSource
   {
      #region Fields

      private readonly List<Action> _actions;
      private volatile int _isCompleted;

      #endregion

      public MockContinuationSource()
      {
         _actions = new List<Action>();
      }

      public void Completed()
      {
         if (_isCompleted == 0)
         {
#pragma warning disable 420
             if (Interlocked.CompareExchange(ref _isCompleted, 1, 0) == 0)
             {
                 InvokeActions();
             }
#pragma warning restore 420
         }
      }

      public IEnumerable<Action> Actions
      {
         get
         {
            return _actions;
         }
      }

      public void ContinueWith(Action action)
      {
         // add action
         lock (_actions)
            _actions.Add(action);

         // may have completed in mean time
         if (_isCompleted == 1)
            InvokeActions();
      }

      private void InvokeActions()
      {
         lock (_actions)
         {
            while (_actions.Count > 0)
            {
               _actions[0]();
               _actions.RemoveAt(0);
            }
         }
      }
   }
}
